<?php

/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class Controller extends CController {

	//render smarty
	public function render($view, $data = null, $return = false) {
		$smarty = Yii :: app()->smarty;
		$data['_currUser'] = Yii::app()->user->name;
		$smarty->assign($data);
		if ($return) {
			return $smarty->fetch($view);
		} else {
			$smarty->display($view);
			return null;
		}
	}

	/**
	 * 检查QueryString中必须要包含一些项
	 * 比如：$this->requireGet('user_id,user_name');
	 *
	 * @param mixed $param $_GET中必须要有的参数
	 * @throws CHttpException 如果有的项没有出现，抛出异常
	 */
	public function requireGet($param) {
		if (is_string($param)) {
			$param = explode(',', $param);
		}
		foreach ($param as $p) {
			$p = trim($p);
			if (!isset ($_GET[$p])) {
				throw new CHttpException(404, "Param '" . $p . "' needed in GET");
			}
		}
	}

	/**
	 * 检查_POST中必须要包含一些项
	 *
	 * @param mixed $param $_POST中必须要有的参数
	 * @throws CHttpException 如果有的项没有出现，抛出异常
	 */
	public function requirePost($param) {
		if (is_string($param)) {
			$param = explode(',', $param);
		}
		foreach ($param as $p) {
			$p = trim($p);
			if (!isset ($_POST[$p])) {
				throw new CHttpException(404, "Param '" . $p . "' needed in POST");
			}
		}
	}

	/**
	 * 检查_REQUEST中必须要包含一些项
	 *
	 * @param mixed $param $_REQUEST中必须要有的参数
	 * @throws CHttpException 如果有的项没有出现，抛出异常
	 */
	public function requireRequest($param) {
		if (is_string($param)) {
			$param = explode(',', $param);
		}
		foreach ($param as $p) {
			$p = trim($p);
			if (!isset ($_REQUEST[$p])) {
				throw new CHttpException(404, "Param '" . $p . "' needed in REQUEST");
			}
		}
	}

    /**
     * @param mixed 要被返回的json数据
     */
    public function renderJson($data) {
        print(CJSON::encode($data));
    }
    
    /**
     * @param $success boolean
     * @param $message string
     * @param $data mixed
     */
    public function renderMyJson($success, $message, $data){
    	$this->renderJson(array('success'=>$success,'message'=>$message,'data'=>$data));
    }
    
	public function renderError($message) {
		$this->renderJson(array('success'=>false,'message'=>$message));
	}
	
}